package dao

import (
	"HiChat/global"
	"HiChat/models"
	"errors"
	"go.uber.org/zap"
)

// GetUserList 获取所有用户
func GetUserList() ([]*models.UserBasic, error) {

	var list []*models.UserBasic
	if tx := global.DB.Find(&list); tx.RowsAffected == 0 {
		return nil, errors.New("未查询到记录")
	}
	return list, nil

}

// FindByNameAndPassWord  通过用户名和密码查询用户
func FindByNameAndPassWord(name string, passWord string) (*models.UserBasic, error) {

	user := models.UserBasic{}

	if tx := global.DB.Where("name = ? and pass_word = ?", name, passWord).First(&user); tx.RowsAffected == 0 {
		return nil, errors.New("未查询到记录")
	}

	return &user, nil

}

// 根据用户名查询，登录时使用

func FindByNameAtLogin(name string) (*models.UserBasic, error) {

	user := models.UserBasic{}

	if tx := global.DB.Where("name = ? ", name).First(&user); tx.RowsAffected == 0 {
		return nil, errors.New("未查询到记录")
	}
	return &user, nil
}

// FindByNameAtRegister 根据用户名查询，注册时使用
func FindByNameAtRegister(name string) (*models.UserBasic, error) {

	user := models.UserBasic{}

	if tx := global.DB.Where("name = ? ", name).First(&user); tx.RowsAffected == 1 {
		return nil, errors.New("当前用户名已存在")
	}
	return &user, nil
}

// FindById 根据id查询
func FindById(id uint) (*models.UserBasic, error) {

	user := models.UserBasic{}

	if tx := global.DB.Where("id = ? ", id).First(&user); tx.RowsAffected == 0 {
		return nil, errors.New("未查到记录")
	}
	return &user, nil
}

// FindByPhone  根据电话号码查询
func FindByPhone(phone string) (*models.UserBasic, error) {

	user := models.UserBasic{}

	if tx := global.DB.Where("phone = ? ", phone).First(&user); tx.RowsAffected == 0 {
		return nil, errors.New("未查到记录")
	}
	return &user, nil
}

// FindByEmail   根据邮箱号码查询
func FindByEmail(email string) (*models.UserBasic, error) {

	user := models.UserBasic{}

	if tx := global.DB.Where("email = ? ", email).First(&user); tx.RowsAffected == 0 {
		return nil, errors.New("未查到记录")
	}
	return &user, nil
}

// CreateUser   新建用户
func CreateUser(user models.UserBasic) (*models.UserBasic, error) {

	if tx := global.DB.Create(&user); tx.RowsAffected == 0 {
		zap.S().Info("新建用户失败")
		return nil, errors.New("创建用户失败")
	}
	return &user, nil
}

// UpdateUser   更新用户
func UpdateUser(user models.UserBasic) (*models.UserBasic, error) {

	tx := global.DB.Model(&user).Updates(models.UserBasic{
		Name:     user.Name,
		PassWord: user.PassWord,
		Gender:   user.Gender,
		Phone:    user.Phone,
		Email:    user.Email,
		Avatar:   user.Avatar,
		Salt:     user.Salt,
	})

	if tx.RowsAffected == 0 {
		zap.S().Info("更新用户失败", user)
		return nil, errors.New("更新用户失败")
	}
	return &user, nil
}

// DeleteUser   删除用户
func DeleteUser(user models.UserBasic) (*models.UserBasic, error) {

	if tx := global.DB.Delete(&user); tx.RowsAffected == 0 {
		zap.S().Info("删除用户失败")
		return nil, errors.New("删除用户失败")
	}
	return &user, nil
}
